#!/bin/bash
#
date_start=$(date +%s)

no=789165
candidate=10
left=10
con=1
sel=0



fail=(708012 708016 708115 708136 708137 708143 708145 708146 708147 708148 708149 708211)

for ((i=0; i<$no; i++));do
	array[$i]=0
done


#get first test number

current_temp1=$RANDOM
current_temp2=$RANDOM
current=`expr $current_temp1 % 1000 \* 1000 + $current_temp2 % 1000`
let "current%=$no"
#echo first current is $current

#start testing

while [[ $con -eq 1 ]]
do
#echo while----1==============$number
let "array[$current]+=1"

#compare with failure number
	for ((xx=0; xx<${#fail[@]}; xx++));do
	if
	[[ $current -eq ${fail[$xx]} ]];
	then
	let "con-=1"
	date_detect=$(date +%s)
	time=$((date_detect-date_start))
	#echo The first error detected, used $time seconds.
	echo $sel
	break 2;
	fi
	done

selected[$sel]=$current
let "sel+=1"

#get candidates

k=0
let "left_temp=$no-${#selected[@]}"
#echo left is $left_temp
#if
#[[ $left_temp -ge $candidate ]];
#then
while [[ $k -lt $candidate ]]
do
#echo while----2==============$number, selected is ${#selected[@]}

	ran1=$RANDOM
	ran2=$RANDOM
	number=`expr $ran1 % 1000 \* 1000 + $ran2 % 1000`

	let "number%=$no"
	
	if
	[[ ${array[$number]} -eq 0 ]];
	then
#echo value of number is ${array[$number]}
#echo number is $number
	let "array[$number]+=1"

	can[$k]=$number
	#echo $k
	(( k++ ))
	#elif
	#[[ $left_temp -ge $candidate ]];
	fi
done
#else
#break;
#fi



#get forgetting set

let "forget_temp=${#selected[@]}-$left"

if [ $forget_temp -ge 0 ]; then
nn=0
for ((n=$forget_temp; n<${#selected[@]}; n++))
do
	after_forget_set[$nn]=${selected[$n]}
	let "nn+=1"
done
else 
for ((n=0; n<${#selected[@]}; n++))
do
	after_forget_set[$n]=${selected[$n]}
done
fi

#calculate distance
for ((y=0; y<${#can[@]}; y++));
do
min=$no
	for ((z=0; z<${#after_forget_set[@]}; z++));
		do
		let "temp=${after_forget_set[$z]}-${can[$y]}"
		if [ $temp -lt 0 ]; then
 			let "temp=0-$temp"
		fi

		if [ $temp -lt $min ]; then
			min=$temp
		fi
		done
mini[$y]=$min
done

max=0
m_temp=0
for ((m=0; m<${#mini[@]}; m++));
do

		if [ ${mini[$m]} -gt $max ]; then
 			max=${mini[$m]} #have not consider the situation that there are more than one choice
			next=${can[$m]}	
			m_temp=$m
		fi
done

current=$next
#echo next is $next
#echo value1 is ${array[${can[1]}]}

for ((m=0; m<${#mini[@]}; m++));
do
	array[${can[$m]}]=0
done
#echo value2 is ${array[${can[1]}]}

array[${can[$m_temp]}]=1


#echo new current is $current, size of can is ${#can[@]}, selected is ${#selected[@]}
unset mini
unset can
unset after_forget_set

done
#testing end
